package com.lagou.server;

import com.lagou.handler.UserServerHandler;
import com.lagou.service.protocol.*;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.context.ApplicationContext;

public class ServerBootstrap {

    public String hostName;
    public int port;

    public ServerBootstrap(String hostName, int port,ApplicationContext applicationContext) {
        this.hostName = hostName;
        this.port = port;
        this.applicationContext=applicationContext;
    }
    private ApplicationContext applicationContext;

    public void start() throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
        serverBootstrap.group(bossGroup,workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
//                        pipeline.addLast(new RpcEncoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new RpcEncoder(RpcResponse.class,new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler(applicationContext));

                    }
                });
        ChannelFuture future = serverBootstrap.bind(hostName, port).sync();


    }



}
